package com.huazhi.wzsnw.controller;

import com.huazhi.wzsnw.constant.CommonUser;
import com.huazhi.wzsnw.exception.BusinessException;
import com.huazhi.wzsnw.exception.ErrorCode;
import com.huazhi.wzsnw.mapper.BackupMapper;
import com.huazhi.wzsnw.mapper.VillageMapper;
import com.huazhi.wzsnw.model.*;
import com.huazhi.wzsnw.model.po.*;
import com.huazhi.wzsnw.service.*;
import com.huazhi.wzsnw.util.AuthtreeUtil;
import com.huazhi.wzsnw.util.DBBackup;
import com.huazhi.wzsnw.util.Md5Util;
import com.huazhi.wzsnw.util.PropertyUtil;
import com.huazhi.wzsnw.util.tcp.StartListen;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/system")
public class SystemController {
    @Autowired
    private SystemService systemService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private LogService logService;
    @Autowired
    private EarlyWarningService earlyWarningService;
//    @Autowired
//    private InspectionService inspectionService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private UserDepService userDepService;
    @Autowired
    private VillageMapper villageMapper;
    @Autowired
    private AlertValueService alertValueService;
    @Autowired
    private BackupMapper backupMapper;

    //系统属性
    @RequiresPermissions("sys:att:view")
    @RequestMapping(value = "/getMongoSearchStructure", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView testMongoSearchStructure(HttpServletRequest request, HttpSession httpSession) {
        try {
            Map result = null;
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            String key = request.getParameter("key");
            Integer limits = Integer.valueOf(limit);
            Integer pages = Integer.valueOf(page);
            result = systemService.getMongoStructure(pages, limits, "mainStructure", key);
            System.out.print("~");
            return json(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/getMongoStructureExsit", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getMongoStructureExsit(HttpServletRequest request, HttpSession httpSession) {
        try {
            Boolean result = null;
            String key = request.getParameter("key");
            String value = request.getParameter("value");
            result = systemService.getValueExsit("mainStructure", key, value);
            System.out.print("~");
            if (result) {
                return json(true);
            } else {
                return json(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/addStructure", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView testMongoAdd(HttpServletRequest request, HttpSession httpSession, @RequestParam Map<String, Object> map) {
        try {
            systemService.addStructure(map, "mainStructure");
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_ADD);
        }
    }

    @RequestMapping(value = "/getOneStructure", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getOneStructure(HttpServletRequest request, HttpSession httpSession) {
        try {
            Map result = null;
            String id = request.getParameter("id");
            if (id.equals("maintainStateTid")) {
                JSONObject jsonObject = new JSONObject();
                List<Document> list = new ArrayList<Document>();
                Document document = new Document();
                document.put("name", "maintainState");
                list.add(document);
                jsonObject.put("code", 0);
                jsonObject.put("msg", "");
                jsonObject.put("count", "0");
                jsonObject.put("data", list);
                return json(jsonObject);
            } else {
                result = systemService.getOneStructure(id, "mainStructure");
            }
            return json(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }

    }

    @RequestMapping(value = "/updateStructure", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView testMongoUpdateStructure(HttpServletRequest request, HttpSession httpSession, @RequestParam Map<String, Object> map) {
        try {
            String id = request.getParameter("id");
            systemService.updateStructure(map, id, "mainStructure");
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }

    }

    @RequestMapping(value = "/updateStructureState", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView updateStructureState(HttpServletRequest request, HttpSession httpSession) {
        List result = null;
        String id = request.getParameter("id");
        String state = request.getParameter("state");
        try {
            systemService.updateStructureState("state", state, id, "mainStructure");
            System.out.print("~");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json(result);
    }

    @RequestMapping(value = "/updateStructureIsvalidate", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView updateStructureIsvalidate(HttpServletRequest request, HttpSession httpSession) {
        List result = null;
        String id = request.getParameter("id");
        String isValidate = request.getParameter("isValidate");
        try {
            systemService.updateStructureState("isValidate", isValidate, id, "mainStructure");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json(result);
    }

    //数据字段
    @RequestMapping(value = "/getTreeStructure", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getTreeStructure(HttpServletRequest request, HttpSession httpSession) {

        JSONObject result = new JSONObject();
        try {
            JSONArray jsonArray = systemService.getTreeStructure();
            result.put("msg", "操作成功");
            result.put("code", 0);
            result.put("data", jsonArray);
            return json(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);

        }
    }

    @RequiresPermissions("sys:dic:view")
    @RequestMapping(value = "/getStructureDetail", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getStructureDetail(HttpServletRequest request, HttpSession httpSession) {
        Map result = null;
        try {
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            String key = request.getParameter("id");
            Integer pages = Integer.valueOf(page);
            Integer pageSize = Integer.valueOf(limit);
            result = systemService.getSelectStructure(pages, pageSize, "selectTable", key);
            System.out.print("~");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json(result);
    }

    @RequestMapping(value = "/getCodeExsit", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getCodeExsit(HttpServletRequest request, HttpSession httpSession) {
        Boolean result = null;
        try {
            String key = request.getParameter("key");
            String value = request.getParameter("value");
            String id = request.getParameter("id");
            result = systemService.getCodeExsit("selectTable", key, value, id);
            System.out.print("~");
            if (result) {
                return json(true);
            } else {
                return json(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json("false");
    }

    @RequestMapping(value = "/addCode", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView addCode(HttpServletRequest request, HttpSession httpSession, @RequestParam Map<String, String> map) {
        try {
            systemService.addCode(map, "selectTable");
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_ADD);
        }
    }

    @RequestMapping(value = "/deleteAttributeById", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView deleteAttributeById(HttpServletRequest request, HttpSession httpSession, @RequestParam Map<String, String> map) {
        try {
            String id = request.getParameter("id");
            systemService.deleteAttributeById(id, "mainStructure");
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_DEL);
        }
    }

    @RequestMapping(value = "/backups",method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView backups(Model model, HttpServletRequest request, HttpSession httpSession) {
        String path = PropertyUtil.getText("backupDir");
        Map<String,String> back=DBBackup.backup(path);
        User user = CommonUser.getUser();
        if(back!=null){
            String name=back.get("name");
            String url=back.get("url");
            Backup backup=new Backup();
            backup.setTid(UUID.randomUUID().toString());
            backup.setNameurl(name);
            backup.setUsertid(user.getTid());
            backup.setUrl(url);
            backup.setBackupdate(new Date());
            backupMapper.insertSelective(backup);
            logService.getAddLog("安全保密管理", "设备初始参数备份", user.getUsername() + "数据库备份");
        }else{
            return  json("error");
        }
        return json(back);
    }

    @RequestMapping(value = "/getDBFile", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getDBFile( Model model
            , HttpServletRequest request,HttpSession httpSession) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject result = new JSONObject();
        int number=1;
        try {
            List<Backup> backupList=backupMapper.selectAll();
            if(backupList.size()!=0) {
                for (Backup backup : backupList) {
//                    backup.setBackupdates(sdf.format(backup.getBackupdate()));
                    backup.setNumber(number);
                    number++;
                }
            }
            result.put("code", "0");
            result.put("msg", "success");
            result.put("data", backupList);
            logService.getAddLog("安全保密管理", "设备初始参数备份", "查询信息");
            return json(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "/restoreDB", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView restoreDB(Model model, HttpServletRequest request,
                                  HttpSession httpSession) {
        Integer result = null;
        try {
            String path = PropertyUtil.getText("backupDir");
            String dbName = request.getParameter("key");
            path = path+"/backup";
            result = DBBackup.load(path,dbName);
            if(result==1){
                User user = CommonUser.getUser();
                logService.getAddLog("安全保密管理", "设备初始参数备份", "恢复数据库");
                return json("yes");
            }else{
                return json("error");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return json("error");
        }

    }


    //department
    @RequiresPermissions("sys:dep:view")
    @RequestMapping(value = "/departmentList", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView departmentList(HttpServletRequest request, HttpSession httpSession) {
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String search = request.getParameter("key");
            List<String> keys = new ArrayList<String>();
            if ("".equals(search) || search == null) {
                keys.add("");
            } else if (!"".equals(search) && search.indexOf(" ") != -1) {
                keys = Arrays.asList(search.split(" "));
            } else if (!"".equals(search) && search.indexOf(" ") == -1) {
                keys.add(search);
            }
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            Integer pages = Integer.valueOf(page);
            Integer limits = Integer.valueOf(limit);
            Integer pageIndex = (pages - 1) * limits;
            Integer pageSize = Integer.valueOf(limit);
            List<String> list = new ArrayList<String>();
            Boolean firstSearch = true;
            for (String oneParam : keys) {
                if (firstSearch) {
                    list = departmentService.getDepartmentBySearch(oneParam);
                    firstSearch = false;
                } else {
                    List<String> middleList = departmentService.getDepartmentBySearch(oneParam);
                    list.retainAll(middleList);
                }
            }
            List<Department> departmentList = new ArrayList<Department>();
            if (list.size() == 0) {
                jsonObject.put("data", false);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "");
            } else {
                int total = list.size();
                departmentList = departmentService.findPagingByListTid(list, pageIndex, pageSize);
                for (int i = 0; i < departmentList.size(); i++) {
                    Date date = departmentList.get(i).getCreatetime();
                    departmentList.get(i).setCreatetimestring(simpleDateFormat.format(date));
                }
                jsonObject.put("data", departmentList);
                jsonObject.put("count", total);
                jsonObject.put("msg", "");
            }
            jsonObject.put("code", 0);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("data", false);
            jsonObject.put("count", 0);
            jsonObject.put("msg", "");
        }
        return json(jsonObject);
    }

    @RequestMapping(value = "/departmentNameExist", method = RequestMethod.POST)
    public ModelAndView departmentNameExist(Model model, HttpServletRequest request,
                                            HttpSession httpSession) {
        String departmentname = request.getParameter("departmentname");

        Department department = departmentService.getDepartmentByField("departmentname", departmentname.trim());
        if (department == null) {
            return json(true);
        } else {
            return json(false);
        }
    }

    @RequestMapping(value = "/departmentCodeExist", method = RequestMethod.POST)
    public ModelAndView departmentCodeExist(Model model, HttpServletRequest request,
                                            HttpSession httpSession) {
        String departmentcode = request.getParameter("departmentcode");
        Department department = departmentService.getDepartmentByField(departmentcode, departmentcode.trim());
        if (department == null) {
            return json(true);
        } else {
            return json(false);
        }
    }

    @RequestMapping(value = "/addDepartment", method = RequestMethod.POST)
    public ModelAndView addDepartment(Model model, HttpServletRequest request,
                                      HttpSession httpSession) {
        try {
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String departmentname = request.getParameter("departmentname");
            String departmentcode = request.getParameter("departmentcode");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String createtime = request.getParameter("createtime");
            Department department = new Department();
            department.setTid(UUID.randomUUID().toString());
            department.setDepartmentcode(departmentcode);
            department.setPhone(phone);
            department.setAddress(address);
            department.setDepartmentname(departmentname);
            department.setCreateby(user.getTid());
            if ("".equals(createtime)) {
                department.setCreatetime(new Date());
            } else {
                department.setCreatetime(simpleDateFormat.parse(createtime));
            }
            department.setState("1");
            departmentService.save(department);
//            User user=userService.selectUserTid(usertid);
//            logService.addLog(usertid,"系统用户管理-组织机构管理","添加组织结构",user.getUsername()+"添加-"+departmentname,new Date());
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_ADD);
        }

    }

    @RequestMapping(value = "/selectDepartmentTid", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView selectDepartmentTid(Model model, HttpServletRequest request,
                                            HttpSession httpSession) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String departmentTid = request.getParameter("tid");
        Department department = departmentService.findByTid(departmentTid);
        department.setCreatetimestring(simpleDateFormat.format(department.getCreatetime()));
        return json(department);
    }

    @RequestMapping(value = "/selectDepartmentByTidExist", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView selectDepartmentByTidExist(Model model, HttpServletRequest request,
                                                   HttpSession httpSession) {

        String departmentTid = request.getParameter("tid");
        String departmentname = request.getParameter("departmentname");
        Department department = departmentService.getDepartmentByTidExist(departmentTid, departmentname.trim());
        if (department == null) {
            return json(true);
        } else {
            return json(false);
        }
    }

    @RequestMapping(value = "/updateDepartment", method = RequestMethod.POST)
    public ModelAndView updateDepartment(Model model, HttpServletRequest request,
                                         HttpSession httpSession) {
        try {
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String tid = request.getParameter("tid");
            String departmentname = request.getParameter("departmentname");
            String departmentcode = request.getParameter("departmentcode");
            String createtime = request.getParameter("createtime");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            Department department = departmentService.findByTid(tid);
            department.setDepartmentcode(departmentcode);
            department.setPhone(phone);
            department.setAddress(address);
            department.setDepartmentname(departmentname);
            department.setCreateby(user.getTid());
            if ("".equals(createtime)) {
                department.setCreatetime(new Date());
            } else {
                department.setCreatetime(simpleDateFormat.parse(createtime));
            }
            department.setState("1");
            departmentService.update(department);
//            redisUtil3.hPut(department.getTid(),"departmentname",department.getDepartmentname());
//            redisUtil3.hPut(department.getDepartmentname() ,"departmentname",department.getTid());
//            User user=userService.selectUserTid(usertid);
//            logService.addLog(usertid,"系统用户管理-组织机构管理","修改组织结构",user.getUsername()+"修改-"+departmentname,new Date());
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }
    }

    @RequestMapping(value = "/deleteDepartment", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView deleteDepartment(Model model, HttpServletRequest request,
                                         HttpSession httpSession) {

        try {

            String tid = request.getParameter("tid");
            Department department = departmentService.findByTid(tid);
            department.setState("0");
            departmentService.update(department);
            List<String> stringList=new ArrayList<>();
            stringList.add(tid);
            List<String> strings=userDepService.getListTidByDepTid(stringList);
            for(String s:strings){
                UserDep userDep=userDepService.findByTid(s);
                userDepService.delete(userDep);
            }
//            User user = userService.selectUserTid(usertid);
//
//            String newDepTid = request.getParameter("newDepTid");
//            String productTid = request.getParameter("productTid");
//            if(productTid!=null){
//                userService.changeProductDepName(tid,productTid);
//            }
//            //根据部门查询用户
//            List<User> list=userMapper.selectAlldepTid(tid);
//            if(list.size()!=0) {
//                for (User user1 : list) {
//                    userMapper.updataDep(user1.getTid(), newDepTid);
//                }
//            }
//            logService.addLog(usertid, "系统用户管理-组织机构管理", "删除组织结构", user.getUsername() + "删除-" + department.getDepartmentname(), new Date());
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_DEL);
        }
    }

    //menu
    @RequiresPermissions("sys:menu:view")
    @RequestMapping(value = "/menuList", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView menuList(HttpServletRequest request, HttpSession httpSession) {
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {

//            String page ="1";
//            String limit ="10";
//            Integer pages = Integer.valueOf(page);
//            Integer limits = Integer.valueOf(limit);
//            Integer pageIndex = (pages - 1) * limits;
//            Integer pageSize = Integer.valueOf(limit);
            List<String> list = new ArrayList<String>();
            List<Menu> menuList = menuService.findAll();
            for (Menu menu : menuList) {
                list.add(menu.getTid());
            }
            List<Menu> menus = new ArrayList<Menu>();
            if (list.size() == 0) {
                jsonObject.put("data", false);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "");
            } else {
                int total = list.size();
                menus = menuService.findPagingByListTid(list, null, null);
                for (int i = 0; i < menus.size(); i++) {
                    Date date = menus.get(i).getCreatetime();
//                    menus.get(i).setCreatetimestring(simpleDateFormat.format(date));
                }
                jsonObject.put("data", menus);
                jsonObject.put("count", total);
                jsonObject.put("msg", "ok");
            }
            logService.getAddLog("系统与参数设置管理", "菜单管理", "查询信息");
            jsonObject.put("code", 0);
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }


    @RequestMapping(value = "/getMenuListXmSelect", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getMenuListXmSelect(Model model, HttpServletRequest request, HttpSession httpSession) {
        try {
            List<Vo> rstlist = new ArrayList<Vo>();
            List<Menu> menuList = menuService.findAll();
            List<Vo> vos = new ArrayList<>();
            for (Menu menu : menuList) {
                if (!"3".equalsIgnoreCase(menu.getType())) {
                    Vo vo = new Vo();
                    vo.setTid(menu.getTid());
                    vo.setParentTid(menu.getParentTid());
                    vo.setValue(menu.getTid());
                    vo.setName(menu.getTitle());
                    vo.setDisabled(false);
                    vo.setSelected(false);
                    vos.add(vo);
                }
            }
            rstlist = SystemController.toTree(vos, "0");

            return json(rstlist);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    public static List<Vo> toTree(List<Vo> treeList, String parentTid) {
        List<Vo> retList = new ArrayList<>();
        for (Vo parent : treeList) {
            if (parentTid.equals(parent.getParentTid())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }

    private static Vo findChildren(Vo vo, List<Vo> treeList) {
        for (Vo child : treeList) {
            if (vo.getTid().equals(child.getParentTid())) {
                if (vo.getChildren() == null) {
                    vo.setChildren(new ArrayList<Vo>());
                }
                vo.getChildren().add(findChildren(child, treeList));
            }
        }
        return vo;
    }


    @RequestMapping(value = "/addMenu", method = RequestMethod.POST)
    public ModelAndView addMenu(Model model, HttpServletRequest request,
                                HttpSession httpSession) {
        try {
            String title = request.getParameter("title");
            String parentTid = request.getParameter("parentTid");
            String href = request.getParameter("href");
            String perms = request.getParameter("perms");
            String type = request.getParameter("type");
            String icon = request.getParameter("icon");
            String sort = request.getParameter("sort");
            String delflag = request.getParameter("delflag");


            Menu menu = new Menu();
            menu.setTid(UUID.randomUUID().toString());
            menu.setTitle(title);
            menu.setParentTid(parentTid);
            menu.setType(type);
            if (!("0".equalsIgnoreCase((type)) || "3".equalsIgnoreCase((type)))) {
                menu.setHref(href);
                menu.setIcon("fa " + icon);
                menu.setTarget("_self");
            } else {
                menu.setPerms(perms);
            }
            if ("".equalsIgnoreCase(delflag)) {
                menu.setDelflag("0");
            } else {
                menu.setDelflag("1");
            }
            if ("".equalsIgnoreCase(sort)) {

            } else {
                menu.setSort(Integer.valueOf(sort));
            }
            menu.setCreatetime(new Date());
            logService.getAddLog("系统与参数设置管理", "菜单管理", "新增" + title);
            menuService.save(menu);
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_ADD);
        }

    }

    @RequestMapping(value = "/delMenu", method = RequestMethod.POST)
    public ModelAndView delMenu(Model model, HttpServletRequest request,
                                HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            Menu menu = menuService.findByTid(tid);
            logService.getAddLog("系统与参数设置管理", "菜单管理", "删除" + menu.getTitle());
            menu.setDelflag("0");
            menuService.delete(menu);
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_DEL);
        }
    }


    @RequestMapping(value = "/getMenuByTid", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getMenuByTid(HttpServletRequest request,
                                     HttpSession httpSession, HttpServletResponse response) {
        try {
            String tid = request.getParameter("tid");
            Menu menu = menuService.findByTid(tid);
            if ("0".equalsIgnoreCase(menu.getDelflag())) {

            } else {
                menu.setDelflag("on");
            }
            logService.getAddLog("系统与参数设置管理", "菜单管理", "查看" + menu.getTitle());
            return json(menu);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    @RequestMapping(value = "/updateMenu", method = RequestMethod.POST)
    public ModelAndView updateMenu(Model model, HttpServletRequest request,
                                   HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            String title = request.getParameter("title");
            String parentTid = request.getParameter("parentTid");
            String href = request.getParameter("href");
            String perms = request.getParameter("perms");
            String type = request.getParameter("type");
            String icon = request.getParameter("icon");
            String sort = request.getParameter("sort");
            String delflag = request.getParameter("delflag");
            Menu menu = menuService.findByTid(tid);
            menu.setTitle(title);
            menu.setParentTid(parentTid);
            menu.setType(type);
            if (!("0".equalsIgnoreCase((type)) || "3".equalsIgnoreCase((type)))) {
                menu.setHref(href);
                menu.setIcon("fa " + icon);
                menu.setTarget("_self");
            } else {
                menu.setPerms(perms);
            }
            if ("".equalsIgnoreCase(delflag)) {
                menu.setDelflag("0");
            } else {
                menu.setDelflag("1");
            }
            if ("".equalsIgnoreCase(sort)) {

            } else {
                menu.setSort(Integer.valueOf(sort));
            }
            menu.setCreatetime(new Date());
            logService.getAddLog("系统与参数设置管理", "菜单管理", "修改" + menu.getTitle());
            menuService.update(menu);
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }

    }


    //user
    @RequestMapping(value = "/getDepartmentTree", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getDepartmentTree(Model model, HttpServletRequest request,
                                          HttpSession httpSession) {
        try {
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            JSONObject jsonObject = new JSONObject();
            List<Dtree> listDtree = new ArrayList<Dtree>();
            if ("0".equalsIgnoreCase(user.getIssuper())) {
                List<Department> departmentList = departmentService.getList();
                List<String> deptidList = new ArrayList<>();
                for (Department department : departmentList) {
                    deptidList.add(department.getTid());
                }
                Dtree dtree = new Dtree();
                String str = StringUtils.join(deptidList, ",");
                dtree.setId(str);
                dtree.setParentId("0");
                dtree.setTitle("组织机构");
                dtree.setCheckArr("0");
                listDtree.add(dtree);
                for (Department department : departmentList) {
                    Dtree dtree1 = new Dtree();
                    dtree1.setId(department.getTid());
                    dtree1.setParentId(str);
                    dtree1.setTitle(department.getDepartmentname());
                    dtree1.setCheckArr("0");
                    listDtree.add(dtree1);
                }
            } else {
                List<String> userDepList = userDepService.getListTidByUserTid(user.getTid());
                List<String> strings = new ArrayList<>();
                if (userDepList.size() > 0) {
                    for (String str : userDepList) {
                        UserDep userDep = userDepService.findByTid(str);
                        strings.add(userDep.getDeptid());
                    }
                }
                Dtree dtree = new Dtree();
                String string = StringUtils.join(strings, ",");
                dtree.setId(string);
                dtree.setParentId("0");
                dtree.setTitle("组织机构");
                dtree.setCheckArr("0");
                listDtree.add(dtree);

                for (String str : strings) {
                    Department department = departmentService.findByTid(str);
                    Dtree dtree1 = new Dtree();
                    dtree1.setId(department.getTid());
                    dtree1.setParentId(string);
                    dtree1.setTitle(department.getDepartmentname());
                    dtree1.setCheckArr("0");
                    listDtree.add(dtree1);
                }
            }
            jsonObject.put("data", listDtree);
            jsonObject.put("msg", "操作成功");
            jsonObject.put("code", 0);
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "/getListUser", method = RequestMethod.GET)
    public ModelAndView getListUser(Model model, HttpServletRequest request, HttpSession httpSession) {
        try {
            String search = request.getParameter("key");
            String department = request.getParameter("department");
            if (search == null) {
                search = "";
            }
            List<String> usertid = new ArrayList<>();
            if(department==null||department.equals("")){
                User user=CommonUser.getUser();
                if(user.getIssuper().equals("0")){
                    List<Department> departmentList = departmentService.getList();
                    List<String> deptidList = new ArrayList<>();
                    for (Department department1 : departmentList) {
                        deptidList.add(department1.getTid());
                    }
                    List<String> stringListss=userDepService.getListTidByDepTid(deptidList);
                    for (String s : stringListss) {
                        UserDep userDep = userDepService.findByTid(s);
                        usertid.add(userDep.getUsertid());
                    }
                }else {
                    List<String> depList=new ArrayList<>();
                    List<String> stringListss = userDepService.getListTidByUserTid(user.getTid());
                    for (String s : stringListss) {
                        UserDep userDep = userDepService.findByTid(s);
                        depList.add(userDep.getDeptid());
                    }
                    List<String> listTidByDepTid= userDepService.getListTidByDepTid(depList);
                    for (String s : listTidByDepTid) {
                        UserDep userDep = userDepService.findByTid(s);
                        usertid.add(userDep.getUsertid());
                    }
                }
            }else {
                String[] arr = department.split(",");
                //将字符串数组转换成集合
                List<String> strings1 = Arrays.asList(arr);
                List<String> stringListss = userDepService.getListTidByDepTid(strings1);
                for (String s : stringListss) {
                    UserDep userDep = userDepService.findByTid(s);
                    usertid.add(userDep.getUsertid());
                }
            }
            JSONObject jsonObject = new JSONObject();
            int total = 0;
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            List<String> list = new ArrayList<String>();
            Integer limits = Integer.valueOf(limit);
            Integer pages = Integer.valueOf(page);
            Integer pageIndex = (pages - 1) * limits;
            Integer pageSize = Integer.valueOf(limit);

            List<String> params = new ArrayList<String>();
            if ("".equals(search)) {
                params.add("");
            } else if (!"".equals(search) && search.indexOf(" ") != -1) {
                params = Arrays.asList(search.split(" "));
            } else if (!"".equals(search) && search.indexOf(" ") == -1) {
                params.add(search);
            }
            Boolean firstSearch = true;
            for (String oneParam : params) {
                if (firstSearch) {
                    if(usertid.size()!=0){
                        list = userService.getListTidBySearch(oneParam, usertid);
                    }
                    firstSearch = false;
                } else {
                    if(usertid.size()!=0) {
                        List<String> middleList = userService.getListTidBySearch(oneParam, usertid);
                        list.retainAll(middleList);
                    }
                }
            }
            List<User> userList = new ArrayList<User>();
            if (list.size() == 0) {
                jsonObject.put("data", false);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "");
            } else {
                total = list.size();
                userList = userService.findPagingByListTid(list, pageIndex, pageSize);
                for (User user : userList) {
                    List<String> stringList = new ArrayList<>();

                    List<String> strings = userDepService.getListTidByUserTid(user.getTid());
                    for (String str : strings) {
                        UserDep userDep = userDepService.findByTid(str);
                        Department department1 = departmentService.findByTid(userDep.getDeptid());
                        stringList.add(department1.getDepartmentname());
                    }

                    user.setDeplistname(stringList);
                    /*if ("".equals(user.getPositionTid()) || user.getPositionTid() == null) {
                        user.setPositionname("");
                    } else {
                        Position position = positionService.findByTid(user.getPositionTid());
                        if (position == null) {
                            user.setPositionname("");
                        } else {
                            user.setPositionname(position.getPositionname());
                        }
                    }*/

                    List<Role> roleList = roleService.getRolesByUserTid(user.getTid());
                    String rolename = "";
                    for (Role role : roleList) {
                        rolename = role.getRolename();
                    }
                    user.setRolename(rolename);
                }
                jsonObject.put("data", userList);
                jsonObject.put("count", total);
                jsonObject.put("msg", "");
            }
            jsonObject.put("code", 0);
            logService.getAddLog("机构人员管理", "用户管理", "查询信息");
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/getUserByUserNameExsit", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getUserByUserNameExsit(HttpServletRequest request,
                                               HttpSession httpSession, HttpServletResponse response) {
        try {
            String username = request.getParameter("username");
            User user = userService.findByField("username", username.trim());
            if (user != null) {
                return json(false);
            } else {
                return json(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public ModelAndView addUser(Model model, HttpServletRequest request,
                                HttpSession httpSession) {
        try {
            User user = CommonUser.getUser();
            String username = request.getParameter("username");
            String name = request.getParameter("name");
            String phone = request.getParameter("phone");
            String depTid = request.getParameter("depTid");
            String sex = request.getParameter("sex");
            String password = request.getParameter("password");
            String remarks = request.getParameter("remarks");
            String state = request.getParameter("state");
            String positionTid = request.getParameter("positionTid");

            User user1 = new User();
            String tid = UUID.randomUUID().toString();
            user1.setTid(tid);
            user1.setUsername(username);
            user1.setName(name);
            user1.setPhone(phone);
            String[] arr = depTid.split(",");
            if (!"".equals(depTid)) {
                for (int i = 0; i < arr.length; i++) {
                    UserDep userDep = new UserDep();
                    userDep.setTid(UUID.randomUUID().toString());
                    userDep.setDeptid(arr[i]);
                    userDep.setUsertid(tid);
                    userDepService.save(userDep);
                }
            }
            user1.setPassword(Md5Util.encryption(password, username));
            user1.setSex(sex);
            user1.setRemarks(remarks);
            user1.setPositionTid(positionTid);
            if ("on".equalsIgnoreCase(state)) {
                user1.setState("1");
            } else {
                user1.setState("0");
            }
            user1.setCreateby(user.getTid());
            user1.setCreatetime(new Date());
            user1.setSalt(username);
            int num = (int) ((Math.random() * 9 + 1) * 100000);
            user1.setDiscern(String.valueOf(num));
            userService.save(user1);
            logService.getAddLog("机构人员管理", "用户管理", "添加用户" + username);
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_ADD);
        }
    }

    @RequestMapping(value = "/getDepartmentList", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getDepartmentList(Model model, HttpServletRequest request,
                                          HttpSession httpSession) {
        try {
            JSONObject jsonObject = new JSONObject();
            List<Department> departmentList = new ArrayList<>();
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            if ("0".equalsIgnoreCase(user.getIssuper())) {
                departmentList = departmentService.getList();
            } else {
                List<String> userDepList = userDepService.getListTidByUserTid(user.getTid());
                List<String> strings = new ArrayList<>();
                if (userDepList.size() > 0) {
                    for (String str : userDepList) {
                        UserDep userDep = userDepService.findByTid(str);
                        strings.add(userDep.getDeptid());
                    }
                    for (String str : strings) {
                        Department department = departmentService.findByTid(str);
                        departmentList.add(department);
                    }
                }
            }
            List<FromSelect> fromSelects = new ArrayList<>();
            for (Department department : departmentList) {
                FromSelect fromSelect = new FromSelect();
                fromSelect.setValue(department.getTid());
                fromSelect.setName(department.getDepartmentname());
                fromSelects.add(fromSelect);
            }
            return json(fromSelects);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/getDepartmentLists", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getDepartmentLists(Model model, HttpServletRequest request,
                                           HttpSession httpSession) {
        try {
            JSONObject jsonObject = new JSONObject();
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            List<Department> departmentList = departmentService.getList();
            jsonObject.put("data", departmentList);
            jsonObject.put("count", "");
            jsonObject.put("msg", "");
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }


    @RequestMapping(value = "/updateUserState", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView updateUserState(HttpServletRequest request, HttpSession httpSession) {
        List result = null;
        String tid = request.getParameter("tid");
        String state = request.getParameter("state");
        try {
            User user = userService.findByTid(tid);
            user.setState(state);
            userService.update(user);
            logService.getAddLog("机构人员管理", "用户管理", "修改用户" + user.getName()+"的状态");
            System.out.print("~");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json(result);
    }

    @RequestMapping(value = "/getUserByTid", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getUserByTid(HttpServletRequest request, HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            User user = userService.findByTid(tid);
//            user.getPassword();
            String state = user.getState();
            if ("1".equalsIgnoreCase(state)) {
                user.setState("on");
            } else {
                user.setState("");
            }
            List<String> userDepList = userDepService.getListTidByUserTid(user.getTid());
            List<String> strings = new ArrayList<>();
            if (userDepList.size() > 0) {
                for (String str : userDepList) {
                    UserDep userDep = userDepService.findByTid(str);
                    strings.add(userDep.getDeptid());
                }
                user.setDepList(strings);
            }

            String positionTid = user.getPositionTid();
            if ("".equals(positionTid) || positionTid == null) {

            } else {
                String[] strs = positionTid.split(",");
                //将字符串数组转换成集合
                List<String> stringList = Arrays.asList(strs);
                user.setPositionList(stringList);
            }
            logService.getAddLog("机构人员管理", "用户管理", "查看" + user.getName()+"信息");
            return json(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public ModelAndView updateUser(Model model, HttpServletRequest request,
                                   HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            String name = request.getParameter("name");
            String phone = request.getParameter("phone");
            String depTid = request.getParameter("depTid");
            String sex = request.getParameter("sex");
            String remarks = request.getParameter("remarks");
            String state = request.getParameter("state");
            String positionTid = request.getParameter("positionTid");

            User user1 = userService.findByTid(tid);
            user1.setTid(tid);
            user1.setName(name);
            user1.setPhone(phone);
            if (!"".equals(depTid)) {
                List<String> list = userDepService.getListTidByUserTid(tid);
                if (list.size() > 0) {
                    for (String str : list) {
                        UserDep userDep = userDepService.findByTid(str);
                        userDepService.delete(userDep);
                    }
                }
                String[] arr = depTid.split(",");
                for (int i = 0; i < arr.length; i++) {
                    UserDep userDep = new UserDep();
                    userDep.setTid(UUID.randomUUID().toString());
                    userDep.setDeptid(arr[i]);
                    userDep.setUsertid(tid);
                    userDepService.save(userDep);
                }
            }
            user1.setSex(sex);
            user1.setRemarks(remarks);
            user1.setPositionTid(positionTid);
            if ("on".equalsIgnoreCase(state)) {
                user1.setState("1");
            } else {
                user1.setState("0");
            }
            userService.update(user1);
            logService.getAddLog("机构人员管理", "用户管理", "修改用户" + user1.getName()+"信息");

            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }
    }

    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public ModelAndView deleteUser(Model model, HttpServletRequest request,
                                   HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            User user = userService.findByTid(tid);
            user.setDelflag("0");
            userService.update(user);
            List<String> stringList=userDepService.getListTidByUserTid(tid);
            for(String s:stringList){
                UserDep userDep=userDepService.findByTid(s);
                userDepService.delete(userDep);
            }
            logService.getAddLog("机构人员管理", "用户管理", "删除用户" + user.getName());
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_DEL);
        }
    }

    @RequestMapping(value = "/getSelectUserList", method = RequestMethod.GET)
    public ModelAndView getSelectUserList(HttpServletRequest request){
        try {
            JSONObject jsonObject = new JSONObject();
            List<User> users = userService.getUserList();
            if(users.isEmpty()){
                jsonObject.put("data", false);
                jsonObject.put("msg", "");
            }else{
                jsonObject.put("data", users);
                jsonObject.put("msg", "");
            }
            jsonObject.put("code", 0);
            return json(jsonObject);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/verifyUserPassword",method = RequestMethod.GET)
    public ModelAndView verifyUserPassword(HttpServletRequest request){
        try {
            User user = userService.findByTid(request.getParameter("tid"));
            JSONObject jsonObject = new JSONObject();
            if(user == null){
                jsonObject.put("res","当前用户session过期，请重新登录");
            }else{
                String password = request.getParameter("password");
                if(user.getPassword().equals(Md5Util.encryption(password, user.getUsername()))){
                    jsonObject.put("res","true");
                }else{
                    jsonObject.put("res","旧密码不正确，请重新输入");
                }
            }
            return json(jsonObject);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/updateUserPassword",method = RequestMethod.POST)
    public ModelAndView updateUserPassword(HttpServletRequest request){
        try {
            User user = userService.findByTid(request.getParameter("tid"));
            String password = request.getParameter("newpassword");
            user.setPassword(Md5Util.encryption(password, user.getUsername()));
            userService.update(user);
            return json(true);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }
    }

    //role
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "/getRoleList", method = RequestMethod.GET)
    public ModelAndView getRoleList(Model model, HttpServletRequest request, HttpSession httpSession) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String search = request.getParameter("key");
            if (search == null) {
                search = "";
            }
            JSONObject jsonObject = new JSONObject();
            int total = 0;
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            List<String> list = new ArrayList<String>();
            Integer limits = Integer.valueOf(limit);
            Integer pages = Integer.valueOf(page);
            Integer pageIndex = (pages - 1) * limits;
            Integer pageSize = Integer.valueOf(limit);

            List<String> params = new ArrayList<String>();
            if ("".equals(search)) {
                params.add("");
            } else if (!"".equals(search) && search.indexOf(" ") != -1) {
                params = Arrays.asList(search.split(" "));
            } else if (!"".equals(search) && search.indexOf(" ") == -1) {
                params.add(search);
            }
            Boolean firstSearch = true;
            for (String oneParam : params) {
                if (firstSearch) {
                    list = roleService.getListTidBySearch(oneParam);
                    firstSearch = false;
                } else {
                    List<String> middleList = roleService.getListTidBySearch(oneParam);
                    list.retainAll(middleList);
                }
            }
            List<Role> roles = new ArrayList<Role>();
            if (list.size() == 0) {
                jsonObject.put("data", false);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "");
            } else {
                total = list.size();
                roles = roleService.findPagingByListTid(list, pageIndex, pageSize);
                for (Role role : roles) {
                    role.setCreatetimestring(simpleDateFormat.format(role.getCreatetime()));
                }
                jsonObject.put("data", roles);
                jsonObject.put("count", total);
                jsonObject.put("msg", "");
            }
            jsonObject.put("code", 0);
            logService.getAddLog("机构人员管理", "角色管理", "查询信息");
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }


    @RequestMapping(value = "/getMenuRoleList", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getMenuRoleList(HttpServletRequest request, HttpSession httpSession) {

        try {
            List<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();
            List<Menu> menuList1 = menuService.findPid("0");
            List<Menu> menuList = menuService.findAll();
            for (Menu menu : menuList1) {
                JSONObject jsonObject = new JSONObject();
                List<Authtree> authtreeListyyy = new ArrayList<>();
                Authtree vo = new Authtree();
                vo.setTid(menu.getTid());
                vo.setValue(menu.getTid());
                vo.setName(menu.getTitle());
                vo.setChecked(true);
                vo.setPid(menu.getParentTid());
                List<Authtree> authtrees = new ArrayList<>();
                for (Menu menu1 : menuList) {
                    Authtree vo1 = new Authtree();
                    vo1.setTid(menu1.getTid());
                    vo1.setValue(menu1.getTid());
                    vo1.setName(menu1.getTitle());
                    vo1.setChecked(true);
                    vo1.setPid(menu1.getParentTid());
                    authtrees.add(vo1);
                }
                vo.setList(AuthtreeUtil.toTree(authtrees, menu.getTid()));
                authtreeListyyy.add(vo);
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("trees", authtreeListyyy);
                jsonObject.put("data", jsonObject1);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "获取成功");
                jsonObjectArrayList.add(jsonObject);
            }
            return json(jsonObjectArrayList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/existsRole", method = RequestMethod.POST)
    public ModelAndView existsRole(Model model, HttpServletRequest request,
                                   HttpSession httpSession) {
        String rolename = request.getParameter("rolename");
        Role role = roleService.existsRole(rolename.trim());
        if (role == null) {
            return json(false);
        } else {
            return json(true);
        }
    }

    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    public ModelAndView addRole(Model model, HttpServletRequest request,
                                HttpSession httpSession) {
        try {
            String rolename = request.getParameter("rolename");
            String rolecode = request.getParameter("rolecode");
            String remark = request.getParameter("remark");
            String[] permission0 = request.getParameterValues("permission0[]");
            String[] permission1 = request.getParameterValues("permission1[]");
            String[] permission2 = request.getParameterValues("permission2[]");
            String[] permission3 = request.getParameterValues("permission3[]");
            Role role = new Role();
            String tid = UUID.randomUUID().toString();
            role.setTid(tid);
            role.setRolename(rolename);
            role.setCreatetime(new Date());
            role.setRolecode(rolecode);
            role.setRemark(remark);
            roleService.save(role);
            if (permission0 != null) {
                for (int i = 0; i < permission0.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission0[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            if (permission1 != null) {
                for (int i = 0; i < permission1.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission1[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            if (permission2 != null) {
                for (int i = 0; i < permission2.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission2[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            if (permission3 != null) {
                for (int i = 0; i < permission3.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission3[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            logService.getAddLog("机构人员管理", "角色管理", "添加角色" + rolename);
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_ADD);
        }

    }

    @RequestMapping(value = "/deleteRole", method = RequestMethod.POST)
    public ModelAndView deleteRole(Model model, HttpServletRequest request,
                                   HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            Role role = roleService.findByTid(tid);
            role.setDelflag("0");
            roleService.update(role);
            logService.getAddLog("机构人员管理", "角色管理", "删除角色"+ role.getRolename());
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_DEL);
        }
    }

    @RequestMapping(value = "/getRoleByTid", method = RequestMethod.POST)
    public ModelAndView getRoleByTid(Model model, HttpServletRequest request,
                                     HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            Role role = roleService.findByTid(tid);
            logService.getAddLog("机构人员管理", "角色管理", "查看角色"+ role.getRolename());
            return json(role);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/getListUserByDepartmentTid", method = RequestMethod.POST)
    public ModelAndView getListUserByDepartmentTid(Model model, HttpServletRequest request,
                                                   HttpSession httpSession) {
        try {
            JSONObject jsonObject = new JSONObject();
            String tid = request.getParameter("tid");
            String roletid = request.getParameter("roletid");
            List<Transfer> transfers = new ArrayList<Transfer>();
            List<String> value = new ArrayList<>();
            if ("".equalsIgnoreCase(tid)) {

            } else {

                List<String> strings = new ArrayList<>();
                strings.add(tid);
                List<String> userDepList = userDepService.getListTidByDepTid(strings);
                List<String> strings1 = new ArrayList<>();
                if (userDepList.size() > 0) {
                    for (String str : userDepList) {
                        UserDep userDep = userDepService.findByTid(str);
                        User user = userService.findByTid(userDep.getUsertid());
                        if (user.getIssuper().equals("0")) {

                        } else {
                            if (user.getDelflag().equals("1")) {
                                strings1.add(user.getTid());
                            }
                        }
                    }

                }

                for (String s : strings1) {
                    List<Role> roleList = roleService.getRolesByUserTid(s);
                    if (roleList.size() != 0) {
                        for (Role role : roleList) {
                            if (role.getTid().equalsIgnoreCase(roletid)) {
                                value.add(s);
                                User user = userService.findByTid(s);
                                Transfer transfer = new Transfer();
                                transfer.setValue(user.getTid());
                                transfer.setTitle(user.getName());
                                transfers.add(transfer);
                            }
                        }
                    } else {
                        User user = userService.findByTid(s);
                        Transfer transfer = new Transfer();
                        transfer.setValue(user.getTid());
                        transfer.setTitle(user.getName());
                        transfers.add(transfer);
                    }
                }
            }

//            List<User> stringList =userService.getUserList();
//            for (User user1 : stringList) {
//                List<Role> roleList = roleService.getRolesByUserTid(user1.getTid());
//                if (roleList.size() != 0) {
//                    for (Role role : roleList) {
//                        if (role.getTid().equalsIgnoreCase(roletid)) {
//                            value.add(user1.getTid());
//                            User user = userService.findByTid(user1.getTid());
//                            Transfer transfer = new Transfer();
//                            transfer.setValue(user.getTid());
//                            transfer.setTitle(user.getName());
//                            transfers.add(transfer);
//                        }
//                    }
//                } else {
//                    User user = userService.findByTid(user1.getTid());
//                    Transfer transfer = new Transfer();
//                    transfer.setValue(user.getTid());
//                    transfer.setTitle(user.getName());
//                    transfers.add(transfer);
//                }
//            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("data", transfers);
            jsonObject1.put("value", value);
            jsonObject.put("data", jsonObject1);
            jsonObject.put("count", "0");
            jsonObject.put("msg", "获取成功");
            jsonObject.put("code", "0");
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/getListUserByDepartmenttidPosition", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getListUserByDepartmenttidPosition(Model model, HttpServletRequest request,
                                                           HttpSession httpSession) {
        try {
            JSONObject jsonObject = new JSONObject();
            String departmenttid = request.getParameter("departmenttid");

            List<String> strings = new ArrayList<>();
            strings.add(departmenttid);
            List<String> userDepList = userDepService.getListTidByDepTid(strings);
            List<String> strings1 = new ArrayList<>();
            if (userDepList.size() > 0) {
                for (String str : userDepList) {
                    UserDep userDep = userDepService.findByTid(str);
                    User user = userService.findByTid(userDep.getUsertid());
                    if (user.getIssuper().equals("0")) {

                    } else {
                        if (user.getDelflag().equals("1")) {
                            strings1.add(user.getTid());
                        }
                    }
                }
            }

            List<User> users = new ArrayList<>();
            for (String s : strings1) {
                User user = userService.findByTid(s);
                Position position = positionService.findByTid(user.getPositionTid());
                if(position!=null){
                    if ("科室主任".equals(position.getPositionname())) {
                        users.add(user);
                    }
                }
            }

            List<FromSelect> fromSelects = new ArrayList<>();
            for (User user : users) {
                FromSelect fromSelect = new FromSelect();
                fromSelect.setValue(user.getTid());
                fromSelect.setName(user.getName());
                fromSelects.add(fromSelect);
            }
            return json(fromSelects);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }


    @RequestMapping(value = "/getListVillageForSelect", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getListVillageForSelect(Model model, HttpServletRequest request,
                                                           HttpSession httpSession) {
        try {
            JSONObject jsonObject = new JSONObject();
            List<Village> villages  =villageMapper.getAllVillage();
            List<FromSelect> fromSelects = new ArrayList<>();
            for (Village user : villages) {
                FromSelect fromSelect = new FromSelect();
                fromSelect.setValue(user.getTid()+"-"+user.getName());
                fromSelect.setName(user.getName());
                fromSelects.add(fromSelect);
            }
            return json(fromSelects);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }




    @RequestMapping(value = "/addAuthorize", method = RequestMethod.POST)
    public ModelAndView addAuthorize(Model model, HttpServletRequest request,
                                     HttpSession httpSession) {
        try {
            String tid = request.getParameter("tid");
            String depTid = request.getParameter("depTid");
            String[] authorize = request.getParameterValues("authorize[]");

            List<String> strings = new ArrayList<>();
            strings.add(depTid);
            List<String> userDepList = userDepService.getListTidByDepTid(strings);
            List<String> strings1 = new ArrayList<>();
            if (userDepList.size() > 0) {
                for (String str : userDepList) {
                    UserDep userDep = userDepService.findByTid(str);
                    User user = userService.findByTid(userDep.getUsertid());
                    if (user.getIssuper().equals("0")) {

                    } else {
                        if (user.getDelflag().equals("1")) {
                            strings1.add(user.getTid());
                        }
                    }
                }
            }

            for (String s : strings1) {
                UserRole userRole = userRoleService.getUserRoleByUserTidAndRoleTid(s, tid);
                if (userRole != null) {
                    userRoleService.delete(userRole);
                }
            }


            if (authorize != null) {
                for (int i = 0; i < authorize.length; i++) {
                    UserRole userRole = new UserRole();
                    userRole.setTid(UUID.randomUUID().toString());
                    userRole.setUsertid(authorize[i]);
                    userRole.setRoletid(tid);
                    userRole.setCreatetime(new Date());
                    userRoleService.save(userRole);
                }
            }
            logService.getAddLog("机构人员管理", "角色管理", "给角色授权");
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_AU);
        }

    }

    @RequestMapping(value = "/getAuthorizeByRoleTid", method = RequestMethod.POST)
    public ModelAndView getAuthorizeByRoleTid(Model model, HttpServletRequest request,
                                              HttpSession httpSession) {
        try {
            JSONObject jsonObject = new JSONObject();
            String tid = request.getParameter("tid");
            List<User> userList = roleService.getListUserByRoleTid(tid);
            jsonObject.put("data", userList);
            jsonObject.put("count", userList.size());
            jsonObject.put("msg", "");
            jsonObject.put("code", "0");
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }


    @RequestMapping(value = "/getMenuRoleListByRole", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getMenuRoleListByRole(HttpServletRequest request, HttpSession httpSession) {

        try {
            String roletid = request.getParameter("tid");
            List<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();
            List<Menu> menuList1 = menuService.findPid("0");
            List<Menu> menuList = menuService.findAll();
            List<String> roleMenus = roleMenuService.getMenuTidByRoleTid(roletid);

            for (Menu menu : menuList1) {
                JSONObject jsonObject = new JSONObject();
                List<Authtree> authtreeListyyy = new ArrayList<>();
                Authtree vo = new Authtree();
                vo.setTid(menu.getTid());
                vo.setValue(menu.getTid());
                vo.setName(menu.getTitle());
                boolean result = roleMenus.contains(menu.getTid());
                if (result) {
                    vo.setChecked(true);
                } else {
                    vo.setChecked(false);
                }
                vo.setPid(menu.getParentTid());
                List<Authtree> authtrees = new ArrayList<>();
                for (Menu menu1 : menuList) {
                    Authtree vo1 = new Authtree();
                    vo1.setTid(menu1.getTid());
                    vo1.setValue(menu1.getTid());
                    vo1.setName(menu1.getTitle());
                    boolean result1 = roleMenus.contains(menu1.getTid());
                    if (result1) {
                        vo1.setChecked(true);
                    } else {
                        vo1.setChecked(false);
                    }
                    vo1.setPid(menu1.getParentTid());
                    authtrees.add(vo1);
                }
                vo.setList(AuthtreeUtil.toTree(authtrees, menu.getTid()));
                authtreeListyyy.add(vo);
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("trees", authtreeListyyy);
                jsonObject.put("data", jsonObject1);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "获取成功");
                jsonObjectArrayList.add(jsonObject);
            }
            return json(jsonObjectArrayList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    @RequestMapping(value = "/existsRoleTid", method = RequestMethod.POST)
    public ModelAndView existsRoleTid(Model model, HttpServletRequest request,
                                      HttpSession httpSession) {
        String roletid = request.getParameter("roletid");
        String rolename = request.getParameter("rolename");
        Role role = roleService.existsRoleTid(roletid, rolename.trim());
        if (role == null) {
            return json(false);
        } else {
            return json(true);
        }
    }

    @RequestMapping(value = "/updateRole", method = RequestMethod.POST)
    public ModelAndView updateRole(Model model, HttpServletRequest request,
                                   HttpSession httpSession) {
        try {

            String tid = request.getParameter("tid");
            String rolename = request.getParameter("rolename");
            String remark = request.getParameter("remark");
            String[] permission0 = request.getParameterValues("permission0[]");
            String[] permission1 = request.getParameterValues("permission1[]");
            String[] permission2 = request.getParameterValues("permission2[]");
            String[] permission3 = request.getParameterValues("permission3[]");
            Role role = roleService.findByTid(tid);
            role.setRolename(rolename);
            role.setRemark(remark);
            roleService.update(role);
            List<RoleMenu> roleMenus = roleMenuService.getRoleMenuByRoleTid(tid);
            for (RoleMenu roleMenu : roleMenus) {
                roleMenuService.delete(roleMenu);
            }

            if (permission0 != null) {
                for (int i = 0; i < permission0.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission0[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            if (permission1 != null) {
                for (int i = 0; i < permission1.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission1[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            if (permission2 != null) {
                for (int i = 0; i < permission2.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission2[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            if (permission3 != null) {
                for (int i = 0; i < permission3.length; i++) {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setTid(UUID.randomUUID().toString());
                    roleMenu.setCreatetime(new Date());
                    roleMenu.setMenutid(permission3[i]);
                    roleMenu.setRoletid(tid);
                    roleMenuService.save(roleMenu);
                }
            }
            logService.getAddLog("机构人员管理", "角色管理", "修改角色"+ role.getRolename()+"权限");
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }

    }

    //log
    @RequiresPermissions("sys:log:view")
    @RequestMapping(value = "/getLogList", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getLogList(HttpServletRequest request, HttpSession httpSession) {
        JSONObject jsonObject = new JSONObject();
        try {
            Calendar calendar = Calendar.getInstance();
            String key = request.getParameter("key");
            String starttime = request.getParameter("starttime");
            String endtime = request.getParameter("endtime");
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            int pages = Integer.parseInt(page);
            int limits = Integer.parseInt(limit);
            Integer pageIndex = (pages - 1) * limits;
            Integer pageSize = Integer.valueOf(limit);
            Date startTime = null, endTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd mm:hh:ss");
            if (starttime != null && !starttime.equals("")) {
                startTime = sdf.parse(starttime);
            }
            if (endtime != null && !endtime.equals("")) {
                endTime = sdf.parse(endtime);
            }
            List<String> listTid = logService.getListTid(startTime, endTime, key);
            if (listTid.size() == 0) {
                jsonObject.put("data", false);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "");
            } else {
                List<Log> logs = logService.findPagingByListTid(listTid, pageIndex, pageSize);
                for (Log log : logs) {
                    log.setCreatetimestring(sdf.format(log.getCreatetime()));
                }
                jsonObject.put("data", logs);
                jsonObject.put("count", listTid.size());
                jsonObject.put("msg", "");
            }
            jsonObject.put("code", 0);
            logService.getAddLog("系统与参数设置管理", "安全日志管理", "查询信息");
            return json(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }



    @RequestMapping(value = "/getPlace", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView getPlace(HttpServletRequest request, HttpSession httpSession, @RequestParam Map<String, String> map) {
        JSONObject result = null;
        try {
            result = systemService.getPlace();
            return json(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.NULL_OBJ);
        }
    }

    @RequestMapping(value = "/updateMenuByTid", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView updateMenuByTid(HttpServletRequest request, HttpSession httpSession) {

        try {
            String tid = request.getParameter("tid");
            String sort = request.getParameter("sort");
            Menu menu = menuService.findByTid(tid);
            if ("".equalsIgnoreCase(sort)) {

            } else {
                menu.setSort(Integer.valueOf(sort));
            }
            menuService.update(menu);
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }
    }

    //预警参数查询
    @RequiresPermissions("sys:basicParameter:view")
    @RequestMapping(value = "/earlyWarningList", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView earlyWarningList(Model model, HttpServletRequest request, HttpSession httpSession) {
        JSONObject result = new JSONObject();
        try {
            List<EarlyWarning> earlyWarningList = earlyWarningService.findAll();
            result.put("count", earlyWarningList.size());
            result.put("code", "0");
            result.put("msg", "success");
            result.put("data", earlyWarningList);
            return json(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }

    //参数设置
    @RequestMapping(value = "/updateEarlyWarning", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView updateEarlyWarning(Model model, HttpServletRequest request, HttpSession httpSession) {
        JSONObject result = new JSONObject();
        try {
            String tid = request.getParameter("tid");
            String value = request.getParameter("value");
            EarlyWarning earlyWarning = earlyWarningService.findByTid(tid);
            earlyWarning.setValue(value);
            earlyWarningService.update(earlyWarning);
            return json(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }
    }

//    //场地设置
//    @RequiresPermissions("sys:basicParameter:view")
//    @RequestMapping(value = "/inspectionSiteList", method = {RequestMethod.POST, RequestMethod.GET})
//    public ModelAndView inspectionSiteList(HttpServletRequest request, HttpSession httpSession) {
//        JSONObject jsonObject = new JSONObject();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        try {
//
//            String page = request.getParameter("page");
//            String limit = request.getParameter("limit");
//            Integer pages = Integer.valueOf(page);
//            Integer limits = Integer.valueOf(limit);
//            Integer pageIndex = (pages - 1) * limits;
//            Integer pageSize = Integer.valueOf(limit);
//            List<String> list = inspectionService.getListTid();
//            List<Inspection> inspectionList = new ArrayList<Inspection>();
//            if (list.size() == 0) {
//                jsonObject.put("data", false);
//                jsonObject.put("count", 0);
//                jsonObject.put("msg", "");
//            } else {
//                int total = list.size();
//                inspectionList = inspectionService.findPagingByListTid(list, pageIndex, pageSize);
//                for (int i = 0; i < inspectionList.size(); i++) {
//                    Date date = inspectionList.get(i).getCreatetime();
//                    inspectionList.get(i).setCreatetimestring(simpleDateFormat.format(date));
//                }
//                jsonObject.put("data", inspectionList);
//                jsonObject.put("count", total);
//                jsonObject.put("msg", "");
//            }
//            jsonObject.put("code", 0);
//            return json(jsonObject);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
//        }
//    }
//

    //position
//    @RequiresPermissions("sys:posi:view")
//    @RequestMapping(value = "/getPositionList", method = {RequestMethod.POST, RequestMethod.GET})
//    public ModelAndView getPositionList(HttpServletRequest request, HttpSession httpSession) {
//        JSONObject jsonObject = new JSONObject();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        try {
//            String search = request.getParameter("key");
//            List<String> keys = new ArrayList<String>();
//            if ("".equals(search) || search == null) {
//                keys.add("");
//            } else if (!"".equals(search) && search.indexOf(" ") != -1) {
//                keys = Arrays.asList(search.split(" "));
//            } else if (!"".equals(search) && search.indexOf(" ") == -1) {
//                keys.add(search);
//            }
//            String page = request.getParameter("page");
//            String limit = request.getParameter("limit");
//            Integer pages = Integer.valueOf(page);
//            Integer limits = Integer.valueOf(limit);
//            Integer pageIndex = (pages - 1) * limits;
//            Integer pageSize = Integer.valueOf(limit);
//            List<String> list = new ArrayList<String>();
//            Boolean firstSearch = true;
//            for (String oneParam : keys) {
//                if (firstSearch) {
//                    list = positionService.getListTidBySearch(oneParam);
//                    firstSearch = false;
//                } else {
//                    List<String> middleList = positionService.getListTidBySearch(oneParam);
//                    list.retainAll(middleList);
//                }
//            }
//            List<Position> positionList = new ArrayList<Position>();
//            if (list.size() == 0) {
//                jsonObject.put("data", false);
//                jsonObject.put("count", 0);
//                jsonObject.put("msg", "");
//            } else {
//                int total = list.size();
//                positionList = positionService.findPagingByListTid(list, pageIndex, pageSize);
//                for (int i = 0; i < positionList.size(); i++) {
//                    Date date = positionList.get(i).getCreatetime();
//                    positionList.get(i).setCreatetimestring(simpleDateFormat.format(date));
//                }
//                jsonObject.put("data", positionList);
//                jsonObject.put("count", total);
//                jsonObject.put("msg", "");
//            }
//            jsonObject.put("code", 0);
//        } catch (Exception e) {
//            e.printStackTrace();
//            jsonObject.put("data", false);
//            jsonObject.put("count", 0);
//            jsonObject.put("msg", "");
//        }
//        return json(jsonObject);
//    }
//
//    @RequestMapping(value = "/positionNameExist", method = RequestMethod.POST)
//    public ModelAndView positionNameExist(Model model, HttpServletRequest request,
//                                          HttpSession httpSession) {
//        String positionname = request.getParameter("positionname");
//        Position position = positionService.getPositionByField(positionname);
//        if (position == null) {
//            return json(true);
//        } else {
//            return json(false);
//        }
//    }
//
//    @RequestMapping(value = "/positionNameExistNotTid", method = RequestMethod.POST)
//    public ModelAndView positionNameExistNotTid(Model model, HttpServletRequest request,
//                                                HttpSession httpSession) {
//        String positionname = request.getParameter("positionname");
//        String tid = request.getParameter("tid");
//        Position position = positionService.getPositionByFieldByNOTID(tid, positionname);
//        if (position == null) {
//            return json(true);
//        } else {
//            return json(false);
//        }
//    }
//
//
//    @RequestMapping(value = "/addPosition", method = RequestMethod.POST)
//    public ModelAndView addPosition(Model model, HttpServletRequest request,
//                                    HttpSession httpSession) {
//        try {
//            User user = CommonUser.getUser();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String positionname = request.getParameter("positionname");
//            String createtimestring = request.getParameter("createtimestring");
//            String remarks = request.getParameter("remarks");
//
//            Position position = new Position();
//            position.setTid(UUID.randomUUID().toString());
//            position.setPositionname(positionname);
//            position.setCreatetime(sdf.parse(createtimestring));
//            position.setRemarks(remarks);
//            position.setCreateby(user.getTid());
//            positionService.save(position);
//            return json(true);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERROR_ADD);
//        }
//    }
//
//    @RequestMapping(value = "/getPositionTid", method = RequestMethod.POST)
//    public ModelAndView getPositionTid(Model model, HttpServletRequest request,
//                                       HttpSession httpSession) {
//        try {
//            User user = CommonUser.getUser();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String tid = request.getParameter("tid");
//            Position position = positionService.findByTid(tid);
//            return json(position);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
//        }
//    }
//
//    @RequestMapping(value = "/updatePosition", method = RequestMethod.POST)
//    public ModelAndView updatePosition(Model model, HttpServletRequest request,
//                                       HttpSession httpSession) {
//        try {
//            User user = CommonUser.getUser();
//            String tid = request.getParameter("tid");
//            String positionname = request.getParameter("positionname");
//            String remarks = request.getParameter("remarks");
//            Position position = positionService.findByTid(tid);
//            position.setPositionname(positionname);
//            position.setRemarks(remarks);
//            positionService.update(position);
//            return json(true);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERROR_UPDATE);
//        }
//    }
//
//    @RequestMapping(value = "/delPosition", method = RequestMethod.POST)
//    public ModelAndView delPosition(Model model, HttpServletRequest request,
//                                    HttpSession httpSession) {
//        try {
//            User user = CommonUser.getUser();
//            String tid = request.getParameter("tid");
//            Position position = positionService.findByTid(tid);
//            positionService.delete(position);
//            return json(true);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERROR_DEL);
//        }
//    }
//
//    @RequestMapping(value = "/getPosition", method = RequestMethod.POST)
//    public ModelAndView getPosition(Model model, HttpServletRequest request,
//                                    HttpSession httpSession) {
//        try {
//            JSONObject jsonObject = new JSONObject();
//            List<Position> positionList = new ArrayList<>();
////            if ("0".equalsIgnoreCase(user.getIssuper())) {
//            positionList = positionService.getList();
////            } else {
////                Department department = departmentService.findByTid(user.getDepTid());
////                departmentList.add(department);
////            }
//            List<FromSelect> fromSelects = new ArrayList<>();
//            for (Position position : positionList) {
//                FromSelect fromSelect = new FromSelect();
//                fromSelect.setValue(position.getTid());
//                fromSelect.setName(position.getPositionname());
//                fromSelects.add(fromSelect);
//            }
//            return json(fromSelects);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
//        }
//    }
//
//    @RequestMapping(value = "/getListPosition", method = RequestMethod.POST)
//    public ModelAndView getListPosition(Model model, HttpServletRequest request,
//                                        HttpSession httpSession) {
//        try {
//            JSONObject jsonObject = new JSONObject();
//            List<Position> positionList = new ArrayList<>();
//            positionList = positionService.getList();
//            jsonObject.put("data", positionList);
//            jsonObject.put("count", "");
//            jsonObject.put("msg", "");
//            return json(jsonObject);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
//        }
//    }

    @RequestMapping(value = "/getAlertValueList",method = RequestMethod.GET)
    public ModelAndView getAlertValueList(HttpServletRequest request){
        try {
            JSONObject jsonObject = new JSONObject();
            List<String> list = alertValueService.getSearchAlertValueListByRequest(request);
            int pageSize = Integer.parseInt(request.getParameter("limit"));
            int pages = Integer.parseInt(request.getParameter("page"));
            Integer pageIndex = (pages - 1) * pageSize;
            if(list.isEmpty()){
                jsonObject.put("data", false);
                jsonObject.put("count", 0);
                jsonObject.put("msg", "");
            }else {
                List<AlertValue> alertValueList = alertValueService.findPagingByListTid(list,pageIndex,pageSize);
                jsonObject.put("data", alertValueList);
                jsonObject.put("count", list.size());
                jsonObject.put("msg", "");
            }
            jsonObject.put("code",0);
            return json(jsonObject);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }
    @RequestMapping(value = "/getAlertValueByKeyExist",method = RequestMethod.GET)
    public ModelAndView getAlertValueByKeyExist(HttpServletRequest request){
        try {
            String key = request.getParameter("key");
            AlertValue alertValue = alertValueService.selectAlertValueByField("key",key.trim());
            if(alertValue == null){
                return json(true);
            }else {
                return json(false);
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }
    @RequestMapping(value = "/addAlertValue",method = RequestMethod.POST)
    public ModelAndView addAlertValue(HttpServletRequest request){
        try {
            AlertValue alertValue = new AlertValue();
            alertValue.setTid(UUID.randomUUID().toString());
            alertValue.setKey(request.getParameter("key"));
            alertValue.setValue(request.getParameter("value"));
            alertValueService.save(alertValue);
            return json(true);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_ADD);
        }
    }
    @RequestMapping(value = "/getAlertValueByTid",method = RequestMethod.GET)
    public ModelAndView getAlertValueByTid(HttpServletRequest request){
        try {
            AlertValue alertValue = alertValueService.findByTid(request.getParameter("tid"));
            return json(alertValue);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_SYSTEM_ROUTE);
        }
    }
    @RequestMapping(value = "/updateAlertValue",method = RequestMethod.POST)
    public ModelAndView updateAlertValue(HttpServletRequest request){
        try {
            AlertValue alertValue = alertValueService.findByTid(request.getParameter("tid"));
            alertValue.setKey(request.getParameter("key"));
            alertValue.setValue(request.getParameter("value"));
            alertValueService.update(alertValue);
            alertValueService.updateAlertValueState(alertValue);
            return json(true);
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR_UPDATE);
        }
    }

    private ModelAndView json(Object result) {
        return new ModelAndView("jsonView").addObject("result", result);
    }
}
